package com.aop.SpElAop.DistributedLock.RedisLock;

/**
 * @Package: com.aop.SpElAop.Lock
 * @ClassName: DistributedLockAspect
 * @Author: h2cloud
 * @CreateTime: 2024/7/9 10:06 下午
 * @Description:
 */

import com.alibaba.fastjson.JSON;
import com.aop.SpElAop.DistributedLock.Lock;
import com.aop.SpElAop.DistributedLock.RedisLock.support.LockFactory;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
@Order(0)
public class RedisLockAspect {
	@Autowired
	private LockFactory lockFactory;

	@Around("@annotation(redisLock)")
	public Object around(ProceedingJoinPoint joinPoint, RedisLock redisLock) throws Throwable {
		Lock lock = lockFactory.getLock(joinPoint, redisLock);
		log.info("↓↓↓ LockInfo ↓↓↓{}{}", System.lineSeparator(), JSON.toJSONString(lock.getLockInfo(), true));
		if (!lock.lock()) {
			throw new Exception(String.format("加锁失败！加锁[%s]失败", lock.getLockInfo().getName()));
		}
		log.info("加锁成功！加锁[{}]成功", lock.getLockInfo().getName());
		try {
			return joinPoint.proceed();
		} finally {
			try {
				lock.unlock();
				log.info("解锁成功！解锁[{}]成功", lock.getLockInfo().getName());
			} catch (Exception e) {
				log.error("解锁失败！解锁[{}]失败", lock.getLockInfo().getName(), e);
			}
		}
	}
}


